//
//  DetailPage.m
//  TodayComment
//
//  Created by 张吉阳 on 15/9/12.
//  Copyright (c) 2015年 xianrenmoshi. All rights reserved.
//

#import "DetailPage.h"
#import "FxGetContent.h"
#import "ContentImageInfo.h"
#import "CommentPage.h"
#import "CommentWidget.h"
#import "DKNightVersion.h"
#import "WeatherPage.h"
#import "FxDBManager.h"
#import "CollectionPage.h"
#import "FxClearChache.h"
#import "DKNightVersion.h"
#import "PCStackMenuItem.h"
#import "PCStackMenu.h"
#import "CommentPage.h"
#import "MyPage.h"
#import "FxActivityIndicator.h"
#import "NightModeSingle.h"
@implementation DetailPage

- (void)viewDidLoad
{
    NightModeSingle *nightMode = [NightModeSingle nightModeShare];
    _nightMode = nightMode.nightTag;
    self.view.nightBackgroundColor = UIColorFromRGB(0x343434);
    _webView.nightBackgroundColor = UIColorFromRGB(0x343434);
   self.barBackgroudImage = @"NavBarWhite";
    [super viewDidLoad];

}


- (void)nightFalls {
    [DKNightVersionManager nightFalling];
}

- (void)dawnComes {
    [DKNightVersionManager dawnComing];
}


- (IBAction)doBack:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)tabBar:(FxTabBar *)tabBar didSelectIndex:(NSInteger)index
{
    
    if (index == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    NSString *path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], CacheImagePath];
    double fileSize = [FxFileUtility calculteFileSzieEx:path]/1024.0/1024.0;
    NSString *fileSizeName = [NSString stringWithFormat:@"%@%.0f%@", @"清除缓存", fileSize, @"兆"];
    if (index == 1) {
        [PCStackMenu showStackMenuWithTitles:
         [NSArray arrayWithObjects: @"我的收藏", fileSizeName, nil]
                                  withImages:[NSArray arrayWithObjects:
                                              [UIImage imageNamed:@"magnifier@2x.png"],
                                              [UIImage imageNamed:@"twitter@2x.png"],
                                               nil]
                                atStartPoint:CGPointMake(tabBar.center.x + 10, tabBar.frame.origin.y - tabBar.frame.size.height - 25)
                                      inView:self.view
                                  itemHeight:40
                               menuDirection:PCStackMenuDirectionClockWiseUp
                                onSelectMenu:^(NSInteger selectedMenuIndex) {
                                    if (selectedMenuIndex == 0) {
                                        CollectionPage *page = [[CollectionPage alloc]init];
                                        [self.navigationController pushViewController:page animated:YES];
                                    }
                                    if (selectedMenuIndex == 1) {
                                        NSString *path = [NSString stringWithFormat:@"%@/%@", [FxGlobal getRootPath], CacheImagePath];
                                        [FxClearChache clearChache:path];
                                    }
                                    
                                }];
        

    }
    if (index == 2) {
        [self collectionNews];

    }
    
}


- (void)viewDidDisappear:(BOOL)animated
{
    
    [super viewDidDisappear:animated];
    [_tabBar removeFromSuperview];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray *array = @[@"nav_back_select@2x.png", @"right_cate_select@2x.png", @"orange_star@2x.png"];
    _tabBar = [[FxTabBar alloc]initWithFrame:CGRectMake(CGRectGetMinX(self.view.frame), (CGRectGetMaxY(self.view.frame)), CGRectGetWidth(self.view.frame), self.view.frame.size.height/13) buttonImages:array];
    _tabBar.delegate = self;
    
    [self.tabBarController.view addSubview:_tabBar];
    [self setNavigationRight:@"contentview_commentbacky.png"];
    
    //[self setNavigationLeft:@"NavigationBackBlack.png"
                        //sel:@selector(doBack:)];
    [self setStatusBarStyle:UIStatusBarStyleDefault];
}

- (void)loadHtml
{
     if (self.conllectJson.length > 0) {
        NSMutableDictionary *dict = [FxJsonUtility jsonValueFromString:self.conllectJson];
        self.contentInfo = [ContentInfo infoFromDict:dict];
        [self webViewLoadHTMLString];
     }
     else{
      [self showIndicator:LoadingTip autoHide:NO afterDelay:NO];
      [self executeContentOp];
     }
}

- (void)executeContentOp
{
    NSArray *array = [_commentInfo.ID componentsSeparatedByString:@"_"];
    NSString *url = [NSString stringWithFormat:DetailURLFmt, array[0]];
   
    NSDictionary *dictInfo = @{@"url":url,@"aid":array[0]};

    _operation = [[FxGetContent alloc] initWithDelegate:self opInfo:dictInfo];
    [_operation executeOp];
}

- (void)opSuccess:(ContentInfo *)info
{
    _operation = nil;
    UIView *button = [_webView viewWithTag:100001];
    button.hidden = YES;
    self.contentInfo = info;
    [self webViewLoadHTMLString];
}

- (void)opFail:(NSString *)errorMessage
{
    if ([errorMessage containsString:@"The Internet connection appears to be offline"]) {
        [_tabBar removeTabAtIndex:2];
        [_tabBar removeTabAtIndex:1];
        [self showIndicator:LoadingTip autoHide:YES afterDelay:YES];
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _webView.frame.size.width, _webView.frame.size.height)];
        imageView.image = [UIImage imageNamed:@"nodata_730.png"];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTag:100001];
        button.frame = CGRectMake(button.frame.origin.x, button.frame.origin.y, _webView.frame.size.width/2, _webView.frame.size.height/10);
         button.center = _webView.center;
        [button setTitle:@"点击屏幕,重新加载" forState:(UIControlStateNormal)];
        [button setTitleColor:[UIColor darkGrayColor] forState:UIControlStateHighlighted];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_webView addSubview:button];
        return;
    }
}

- (void)buttonClick:(UIButton *)sender
{
    [super viewDidLoad];

}


- (void)webViewLoadHTMLString
{
    NSString *urlString = [[NSBundle mainBundle] pathForResource:_nightMode ofType:@"html"];
    NSString *htmlString = [self htmlConvert:_contentInfo];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:urlString]];
    });
 
}

- (NSString *)htmlConvert:(ContentInfo *)info
{
    if([info.body containsString:@"使用安卓和iPhone最新版本客户端可获得更流畅体验"]){
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _webView.frame.size.width, _webView.frame.size.height)];
        imageView.image = [UIImage imageNamed:@"nodata_730.png"];
        [_webView addSubview:imageView];
        return nil;
    }
    
    else {
        
        
       NSString *file = [[NSBundle mainBundle] pathForResource:_nightMode ofType:@"html"];
       NSString *html = [[NSString alloc] initWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil];
       html = [html stringByReplacingOccurrencesOfString:HtmlBody withString:info.body];
       html = [html stringByReplacingOccurrencesOfString:HtmlTitle withString:info.title];
       html = [html stringByReplacingOccurrencesOfString:HtmlSource withString:info.source];
       html = [html stringByReplacingOccurrencesOfString:HtmlPTime withString:info.ptime];
    
       if (info.images.count > 0) {
           NSString *img = nil;
        
           for (ContentImageInfo *imageInfo in info.images) {
               img = [NSString stringWithFormat:HtmlImage, imageInfo.src];
               html = [html stringByReplacingOccurrencesOfString:imageInfo.ref withString:img];
           }
        }
        _html = html;
       return html;
    }
    

}

- (void)collectionNews
{
    if([FxDBManager fetchNews:_commentInfo.ID] == nil){
        NSDictionary *dictInfo = @{@"pi":_commentInfo.ID, @"b":_commentInfo.commentContent, @"json":_contentInfo.json};
        [FxDBManager saveNews:dictInfo];
        
        }
}
@end
